import DexieCtx from "@/utils/dexiectx";

const Accounts = {
  state: () => ({
    // 账号是内存+indexedDB，账号状态持久化
    accountsList: null,
  }),
  mutations: {
    SET_ACCOUNTS_LIST(state, list) {
      // 这里的 `state` 对象是模块的局部状态
      state.accountsList = list
    }
  },
  actions: {
    async addAccount({ dispatch }, account) {
      const dexie = await DexieCtx.db()
      const oldAc = await dexie.accounts.get({
        phone: account.phone
      })
      if (oldAc == null) {
        await dexie.accounts.add({ ...account })
      } else {
        account.id = oldAc.id
        await dispatch("updateAccount", account)
      }
      await dispatch("loadAccounts")
    },
    async deleteAccount({ dispatch }, account) {
      const dexie = await DexieCtx.db()
      await dexie.accounts.where("id").equals(account.id).delete()
      await dispatch("loadAccounts")
    },
    async updateAccount({ dispatch }, account) {
      const dexie = await DexieCtx.db()
      let newAccount = { ...account }
      await dexie.accounts.where("id").equals(account.id).modify(newAccount)
      await dispatch("loadAccounts")
    },
    async loadAccounts({ commit }) {
      const dexie = await DexieCtx.db()
      const arr = await dexie.accounts.toArray()
      commit("SET_ACCOUNTS_LIST", arr)
      return arr
    },
    async linkWallets({ state, dispatch }, walletList) {
      const dexie = await DexieCtx.db()
      for (let index = 0; index < state.accountsList.length; index++) {
        if (index >= walletList.length) {
          break
        }
        const account = state.accountsList[index];
        if (account.address != null) {
          continue
        }
        const wallet = walletList[index]
        account.address = wallet.address
        account.mnemonic = wallet.mnemonic
        account.address_user_friendly = wallet.address_user_friendly
        await dexie.accounts.where("id").equals(account.id).modify(account)
      }
      await dispatch("loadAccounts")
    }
  },
  getters: {
    accountsList(state) {
      return state.accountsList
    },
  }
}

export default Accounts